package edu.nepu.flink.api.transform;

import edu.nepu.flink.api.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Date 2024/2/28 20:21
 * @Created by chenshuaijun
 */
public class MapOperator {


    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<WaterSensor> elementSource = env.fromElements(
                new WaterSensor("s1", 1L, 1),
                new WaterSensor("s2", 2L, 11),
                new WaterSensor("s3", 4L, 5)
        );

        // 使用map获取sensor的id
        // map算子的使用方法是有三种：（1）匿名内部类（2）lambda表达式（3）创建一个类实现MapFunction的接口
        // TODO 使用第一种方式
        SingleOutputStreamOperator<String> mapStream1 = elementSource.map(new MapFunction<WaterSensor, String>() {
            @Override
            public String map(WaterSensor value) throws Exception {
                return value.getId();
            }
        });
        mapStream1.print("mapStream1");

        // TODO 使用第二种方式
        SingleOutputStreamOperator<String> mapStream2 = elementSource.map(WaterSensor::getId);
        mapStream2.print("mapStream2");

        // TODO 使用第三种方式
        SingleOutputStreamOperator<String> mapStream3 = elementSource.map(new MapFunctionImp());
        mapStream3.print("mapStream3");


        env.execute();
    }

    static class MapFunctionImp implements MapFunction<WaterSensor,String>{

        @Override
        public String map(WaterSensor value) throws Exception {
            return value.getId();
        }
    }
}
